package com.wp.file.config;

import com.wp.file.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理
 */
@Slf4j
//对注解了RestController和Controller的类开启AOP切面拦截进行异常处理
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody//方法需要返回响应的JSON数据
public class GlobalExceptionHandler {
    /**通用异常处理方法**/
    @ExceptionHandler(Exception.class)
    public R<String> allExceptionHandler(Exception e) {
        e.printStackTrace();
        log.error("全局异常捕获：" + e.getMessage());

        return R.error("全局错误"+e.getMessage());    // 通用异常结果
    }

    @ExceptionHandler(NullPointerException.class)
    //空指针处理方法
    public R<String> exceptionHandler2(NullPointerException e) {
        e.printStackTrace();
        log.error("空指针异常捕获：" + e);
        return R.error(e.toString());
    }

    //下标越界处理方法
    @ExceptionHandler(IndexOutOfBoundsException.class)
    @ResponseBody
    public R<String> exceptionHandler3(IndexOutOfBoundsException e) {
        e.printStackTrace();
        log.error("下标越界异常捕获：" + e);
        return R.error(e.toString());
    }

    @ExceptionHandler(MailException.class)
    public R<String> exceptionHandler4(MailException e){
        e.printStackTrace();
        log.error("邮件发送失败异常: "+e.toString());
        return R.error(e.toString());
    }
}
